// pages/user/index.js
var app = getApp();
var rootDocment = app.globalData.postUrl;
const defaultAvatarUrl = 'https://lhs.tann.cc/upload/pic/public/tx.jpg'
Page({
    /**
     * 页面的初始数据
     */
    data: {
        navHeight: app.globalData.barInfo.navHeight, //导航栏高度
        topOpacity: 0,

        bottomHeight: 0,
        rootUrl: rootDocment,
        hiddenLoading: false,
        userInfo: {},
        integral: 0,
        balance: 0,
        commission: 0,
        level: '',
        orderNum: {
            state0: 0,
            state1: 0,
            state2: 0,
            state3: 0
        },
        fenxiao: {
            orderNum: 0,
            teamNum: 0,
            allMoney: 0,
        },
        avatarUrl: defaultAvatarUrl,
        nickName: wx.getStorageSync('nickName'),
        logonShow: false,
        avatars: defaultAvatarUrl,
        logonList: [],
        vip_express_time: '',
        meIsShow: true,
        condeShow: false,
        ewmImg: '',
        meIsShows: true,
        fenhongchi: {},
        obj_user_info: {},
        couponNum: 0,
        uid: wx.getStorageSync('user_id3') || ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            bottomHeight: app.globalData.bottomHeight
        })

        app.editTabbar();
        let arr = ['J8xfVd-OfPgGZvrvcZUmVZPalU0LJfvCuemjzrVkpAs', 'GZQNbaOX4wp9toy-Go3QhyUg4VQEj-rt-lryVqBmHjc']
        wx.requestSubscribeMessage({
            tmplIds: arr, // 最多支持3条
            success(res) {
                console.log(res, '0099090090');

            },
            fail(err) {
                console.log(err, '88888888');
            }
        })
        // this.data_vip_list()
    },
    // 头像
    onChooseAvatar(e) {
        if (!wx.getStorageSync('user_id3')) {
            this.goLoginBtn()
            return
        }

        let t = this
        const {
            avatarUrl
        } = e.detail
        this.setData({
            avatarUrl,
        })
        wx.setStorageSync('avatarUrl', this.data.avatarUrl)
        wx.uploadFile({
            url: rootDocment + '/api/user/z_upload',
            name: 'up_file',
            filePath: avatarUrl,
            header: {},
            formData: {
                up_file: this.data.avatarUrl,
            },
            success: (res) => {
                var paraArr = new Array();
                var sign = app.signature(paraArr);
                const url = JSON.parse(res.data)
                console.log(url)
                this.setData({
                    avatarUrl: url.data.image_url
                })
                wx.setStorageSync('userImage', url.data.image_url)
                var paraArr = new Array();
                paraArr['user_id'] = this.data.userInfo.userID;
                wx.request({
                    url: rootDocment + '/api/user/z_save_avatar',
                    method: "POST",
                    data: {
                        avatar: url.data.image_url,
                        id: paraArr['user_id'],
                        sign: sign
                    },
                    success(res) {
                        t.getMind()
                        console.log(res, 'sign======', url.data.image_url, paraArr['user_id'])
                    }
                })

            }
        })

    },
    // 输入/修改昵称
    clickPopup() {
        // let arr = ['J8xfVd-OfPgGZvrvcZUmVZPalU0LJfvCuemjzrVkpAs', 'GZQNbaOX4wp9toy-Go3QhyUg4VQEj-rt-lryVqBmHjc']
        // wx.requestSubscribeMessage({
        //   tmplIds: arr, // 最多支持3条
        //   success(res) {
        //     console.log(res, '0099090090');
        //     // 'accept'表示用户同意订阅该条id对应的模板消息
        //     // if (res[''] === 'accept') {
        //     //   // 用户同意订阅，调用云函数或服务器接口发送订阅消息

        //     // }
        //   },
        //   fail(err) {
        //     console.log(err, '88888888');
        //   }
        // })

        let that = this
        wx.showModal({
            title: '设置昵称',
            placeholderText: '请输入您的昵称',
            editable: true,
            confirmColor: '#ff0000',
            success(res) {
                var paraArr = new Array();
                var sign = app.signature(paraArr);
                paraArr['user_id'] = that.data.userInfo.userID;
                if (res.confirm) {
                    console.log(res, '用户点击确定')
                    that.setData({
                        nickName: res.content
                    })
                    wx.request({
                        url: rootDocment + '/api/user/z_save_nickname',
                        method: 'POST',
                        data: {
                            id: paraArr['user_id'],
                            nickname: res.content,
                            sign: sign
                        },
                        success(val) {
                            console.log(val, '昵称')
                            that.getMind()
                        }
                    })
                    wx.setStorageSync('nickName', res.content)
                }
            }
        })
    },
    // 登录进来获取头像/昵称
    getMind() {
        var that = this
        var paraArr = new Array();
        var sign = app.signature(paraArr);
        paraArr['user_id'] = that.data.userInfo.userID;
        wx.request({
            url: rootDocment + '/api/user/z_getinfo',
            method: 'POST',
            data: {
                id: paraArr['user_id'],
                sign: sign
            },
            success(res) {
                console.log(res.data.data.avatar == "https://lhs.tann.cc/upload/pic/public/tx.jpg", '-==-=-=-99999999999');

                if (res.data.data.avatar == "https://lhs.tann.cc/upload/pic/public/tx.jpg" || res.data.data.avatar == "") {
                    that.setData({
                        meIsShows: false
                    })

                    return
                }
                if (res.data.data.nickname == "") {
                    that.setData({
                        meIsShows: false
                    })

                    return
                }
                that.setData({
                    nickName: res.data.data.nickname,
                    avatarUrl: res.data.data.avatar
                })
                that.getLogon()
            }
        })
    },
    //下拉刷新
    onPullDownRefresh: function () {
        var that = this;
        app.globalData.userInfo.userID = '';
        //用户授权登录
        app.login(function (userInfo) {
            that.setData({
                userInfo: userInfo
            });
            that.getUserInfo();
            that.getLogon()
        });
        wx.stopPullDownRefresh();
    },

    //获取列表
    getCouponList: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['state'] = 1
        paraArr['user_id'] = that.data.userInfo.userID;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api/coupon/index',
            data: {
                state: paraArr['state'],
                user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                that.setData({
                    couponNum: res.data.length || 0
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this

        if (wx.getStorageSync('user_id3')) {
            app.login(function (userInfo) {
                that.setData({
                    userInfo: userInfo,
                });

                that.getUserInfo();
                that.getOrderNum();
                that.getFenxiaoInfo();
                that.getMind()
                that.getLogon()
                that.getCouponList()
            });
        }

    },

    goLoginBtn() {
        let that = this
        app.login(function (userInfo) {
            that.setData({
                userInfo: userInfo
            });
            that.getUserInfo();
            that.getOrderNum();
            that.getFenxiaoInfo();
            that.getMind()
            that.getLogon()
        });
    },


    // 获取当前是几号 26号会员日弹窗
    getWeekByDate(dates) {
        var currentDate = new Date(); // 创建一个Date对象，表示当前时间
        var day = currentDate.getDate(); // 获取当前日期，即几号
        const startTime = new Date(2025, 2, 15, 0, 0, 0); // 2025-03-15 00:00:00
        const endTime = new Date(2025, 2, 20, 0, 0, 0); // 2025-03-20 00:00:00

        // // 判断逻辑
        // let isActive = () => {
        //   const now = new  Date();
        //   return now >= startTime && now < endTime;
        // }

        // if (isActive() == true) {
        //   return true
        // } else if (day == '26') {
        //   return true
        // } else {
        //   return false
        // }
        if (day == '26') {
            return true
        } else {
            return false
        }

        // let show_day = new Array('7', '1', '2', '3', '4', '5', '6');
        // let date = new Date(dates);
        // date.setDate(date.getDate());
        // let day = date.getDay();
        // return show_day[day];
    },

    //周三会员商品
    data_vip_list() {
        var that = this;
        var paraArr = new Array();
        paraArr['size'] = "8";
        paraArr['type'] = 'member_day';
        // paraArr['user_id'] = 'member_day';
        // member_day
        // 99_vip
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_goods',
            data: {
                size: paraArr['size'],
                type: paraArr['type'],
                // user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                that.setData({
                    vip_list: res.data.data
                });

            }
        })
    },

    /**
     * 获取用户信息
     */
    getUserInfo: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['id'] = that.data.userInfo.userID;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_user/' + paraArr['id'],
            data: {
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                that.setData({
                    // nickname: res.data.data.nickname,
                    // avatar: res.data.data.avatar,
                    obj_user_info: res.data.data,
                    integral: res.data.data.integral,
                    balance: res.data.data.balance,
                    commission: res.data.data.commission,
                    level: res.data.data.level_id,
                    user_id: res.data.data.user_id,
                    is_vip: res.data.data.is_vip,
                    leave_nums: res.data.data.leave_nums,
                    is_shop: res.data.data.is_shop,
                    mobile: res.data.data.mobile,
                    vip_express_time: res.data.data.vip_express_time,
                    ewmImg: res.data.data.code
                });

                wx.setStorageSync('is_vip', res.data.data.is_vip)
                wx.setStorageSync('is_shop', res.data.data.is_shop)
                wx.setStorageSync('owner_shop_name', res.data.data.owner_shop_name)
                console.log(!res.data.data.avatar || !res.data.data.nickname, ')_)_)_)_)_))');
                if (!res.data.data.avatar || !res.data.data.nickname) {
                    that.setData({
                        meIsShow: false
                    })
                    wx.setStorageSync('meIsShow', that.data.meIsShow)
                } else {
                    that.setData({
                        meIsShow: true
                    })
                    wx.setStorageSync('meIsShow', true)
                }
            }
        })
        var paraArrs = new Array();
        paraArrs['user_id'] = that.data.userInfo.userID;
        var signs = app.signature(paraArrs);
        wx.request({
            url: rootDocment + '/api/llgn/fenhongchi',
            data: {
                user_id: paraArrs['user_id'],
                sign: signs
            },
            method: 'GET',
            header: {},
            success: function (res) {
                that.setData({
                    fenhongchi: res.data.data
                });


            }
        })

    },

    /**
     * 获取各订单数量
     */
    getOrderNum: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['user_id'] = that.data.userInfo.userID;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api/comm_get/getOrderNum',
            data: {
                user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                that.setData({
                    'orderNum.state0': res.data.state0,
                    'orderNum.state1': res.data.state1,
                    'orderNum.state2': res.data.state2,
                    'orderNum.state3': res.data.state3,
                    'orderNum.state4': res.data.state4,
                });
                // if (res.data.have_mobile == 0) {
                //  wx.navigateTo({
                //   url: '/pages/shouji/shouji',
                // })
                // }

            }
        })
    },

    /**
     * 获取会员分销信息
     */
    getFenxiaoInfo: function () {
        var that = this;
        if (that.data.userInfo.isFX) {
            var paraArr = new Array();
            paraArr['user_id'] = that.data.userInfo.userID;
            var sign = app.signature(paraArr);
            wx.request({
                url: rootDocment + '/api/fenxiao/getFenxiaoInfo',
                data: {
                    user_id: paraArr['user_id'],
                    sign: sign
                },
                method: 'GET',
                header: {},
                success: function (res) {
                    that.setData({
                        'fenxiao.orderNum': res.data.orderNum,
                        'fenxiao.teamNum': res.data.teamNum,
                        'fenxiao.allMoney': res.data.allMoney
                    });
                }
            })
        }
    },
    // 去申请开店页面
    openShop() {
        if (!wx.getStorageSync('user_id3')) {
            this.goLoginBtn()
            return
        }

        if (this.data.is_shop >= 1) {
            wx.navigateTo({
                url: `/pages/hhrCore/index`,
            })
        } else {
            wx.navigateTo({
                url: `/pages/openShop/openInfo`,
            })
        }
    },
    //获取分享图
    getQrcode: function () {
        if (!wx.getStorageSync('user_id3')) {
            this.goLoginBtn()
            return
        }

        var that = this;
        if (that.data.showPic) {
            that.setData({
                showPic: !that.data.showPic
            });
        } else {
            that.setData({
                showShare: false,
            });

            wx.showLoading({
                title: '加载中'
            })

            var m_page = 'pages/index/index';
            var m_scene = that.data.userInfo.userID;
            var paraArr = new Array();
            paraArr['page'] = m_page;
            paraArr['scene'] = m_scene;
            var sign = app.signature(paraArr);
            wx.request({
                url: rootDocment + '/api/get_qrcode/myQrcode',
                data: {
                    page: m_page,
                    scene: m_scene,
                    sign: sign
                },
                method: 'GET',
                header: {},
                success: function (res) {
                    wx.hideLoading()
                    console.log(res.data.msg);
                    that.setData({
                        hiddenLoading: true
                    });
                    if (res.data.success == true) {

                        that.setData({
                            showPic: !that.data.showPic,
                            sharePic: res.data.msg,
                        });
                    } else {
                        that.setData({
                            hiddenLoading: true
                        });
                        wx.showToast({
                            title: res.data.msg,
                            icon: 'none'
                        })
                    }

                },
                fail: (e) => {
                    wx.hideLoading()
                    that.setData({
                        hiddenLoading: true
                    });
                }
            })
        }
    },

    //保存分享图片
    savePic: function () {
        var that = this;
        wx.downloadFile({
            url: that.data.rootUrl + that.data.sharePic,
            success: function (res) {
                let path = res.tempFilePath
                wx.saveImageToPhotosAlbum({
                    filePath: path,
                    success(res) {
                        wx.showToast({
                            title: '保存成功'
                        })
                    },
                    fail(res) {
                        wx.showToast({
                            title: '保存失败',
                            icon: 'error'

                        })
                    },
                    complete(res) {
                        that.setData({
                            showPic: false
                        });
                    }
                })
            },
            fail: function (res) {
                console.log(res)
            }
        })

    },
    // 登录退出
    logon() {
        this.setData({
            logonShow: true
        })
    },

    showPopup() {
        this.setData({
            logonShow: true
        });
    },

    onClose() {
        this.setData({
            logonShow: false
        });
    },

    onSwitch(e) {
        let item = e.currentTarget.dataset.item
        var that = this;
        var paraArr = new Array();
        paraArr['user_id'] = item.id;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api/user/setDefaultAccount',
            data: {
                user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'POST',
            header: {},
            success: function (res) {
                console.log(res);
                if (res.data.code == 1001) {
                    wx.clearStorageSync()
                    app.globalData.userInfo.userID = ''
                    wx.reLaunch({
                        url: '/pages/authorize/index',
                    })
                }
            }
        })
    },

    getLogon() {
        var that = this;
        var paraArr = new Array();
        paraArr['openid'] = wx.getStorageSync('session_id')
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api/user/getAccountList',
            data: {
                openid: paraArr['openid'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                console.log(res);
                if (res.data.code == 1001) {
                    that.setData({
                        logonList: res.data.data
                    })
                }
            }
        })
    },

    uploadImage() {
        let that = this
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original'],
            sourceType: ['album'],
            success: function (res) {
                console.log(res, 'res')
                var tempFilePaths = res.tempFilePaths;
                wx.showLoading({
                    title: '上传中'
                })
                wx.uploadFile({
                    url: rootDocment + '/api/llgn/uploadImg',
                    filePath: tempFilePaths[0],
                    name: 'up_file',
                    formData: {
                        up_file: tempFilePaths[0],
                        type: 'shop'
                    },
                    success: function (res) {
                        wx.hideLoading()
                        console.log(res)
                        const url = JSON.parse(res.data)
                        console.log(url, 'url')
                        that.setData({
                            ewmImg: url.data.image_url
                        })

                    },
                    fail: function (res) {
                        wx.hideLoading()
                        console.log(res)
                    }
                })

            }
        })
    },

    getPhone(e) {
        this.setData({
            logonShow: false
        })
        var that = this;
        let errMsg = e.detail.errMsg;
        //加密格式
        let iv = e.detail.iv;
        let encry = e.detail.encryptedData;
        let token = wx.getStorageSync('token');
        let phone = wx.getStorageSync('phone');
        console.log(iv)

        //手机号和验证码验证略

        if (errMsg == 'getPhoneNumber:ok') {
            //发送请求
            wx.request({
                url: rootDocment + '/api/logic/decryptionInformation',
                data: {
                    session_key: wx.getStorageSync('session_key'),
                    iv: iv,
                    encryptedData: encry
                },
                header: {},
                success: function (res3) {
                    var shouji = res3.data.msg.result.phoneNumber
                    that.denglu(shouji)
                    wx.setStorageSync('phone', res3.data.msg.result.phoneNumber);
                    //跳转到其他页面
                }
            })
        } else {
            //跳转到通过短信验证码获取手机号页面
            wx.navigateTo({
                url: '/pages/messageCode/messageCode',
            })
        }
    },

    denglu(shouji) {
        wx.request({
            url: rootDocment + '/api/user/bindMobile',
            data: {
                id: wx.getStorageSync('user_id3'),
                mobile: shouji,
            },
            header: {},
            success: function (res3) {
                if (res3.data.success) {
                    var that = this;
                    var paraArr = new Array();
                    paraArr['user_id'] = res3.data.data.id;
                    var sign = app.signature(paraArr);
                    wx.request({
                        url: rootDocment + '/api/user/setDefaultAccount',
                        data: {
                            user_id: paraArr['user_id'],
                            sign: sign
                        },
                        method: 'POST',
                        header: {},
                        success: function (res) {
                            console.log(res);
                            if (res.data.code == 1001) {
                                wx.clearStorageSync()
                                app.globalData.userInfo.userID = ''
                                wx.reLaunch({
                                    url: '/pages/authorize/index',
                                })
                            }
                        }
                    })
                }
            }
        })
    },

    // 上传微信二维码名片
    afterReads_code(event) {
        console.log(event, 11111);
        // 类型，avatar：上传头像；fengcai：上传风采图片；comment：上传评论图片
        let that = this
        const {
            file
        } = event.detail;
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        wx.uploadFile({
            url: rootDocment + '/api/llgn/uploadImg', // 仅为示例，非真实的接口地址
            filePath: file.url,
            name: 'up_file',
            formData: {
                up_file: file.url,
                type: 'shop'
            },
            success(res) {
                let data = JSON.parse(res.data)
                if (data.code == 1001) {
                    console.log(data);
                    const {
                        fileLists_code = []
                    } = that.data;

                    fileLists_code.push({
                        ...file,
                        url: data.data.image_url
                    });
                    that.setData({
                        fileLists_code
                    });

                }
                // 上传完成需要更新 fileList
            },
        });
    },

    onCondeShowe() {
        let is = this.data.condeShow
        this.setData({
            condeShow: !is,
            fileLists_code: []
        })

    },

    btn_code() {
        let t = this
        let is = this.data.condeShow
        if (this.data.ewmImg == '') {
            wx.showToast({
                title: '请先上传二维码',
                icon: 'none'
            })
        }
        // let fileLists_code = []
        // this.data.fileLists_code.forEach((item, index) => {
        //   fileLists_code.push(item.url)
        // })
        // console.log(fileLists_code);
        wx.showLoading({
            title: '上传中',
        })
        wx.request({
            url: rootDocment + '/api/data_grid/qrcode',
            data: {
                user_id: wx.getStorageSync('user_id3'),
                code: t.data.ewmImg,
            },
            method: 'POST',
            header: {},
            success: function (res3) {
                console.log(res3, 'res3');
                // wx.showToast({
                //   title: '上传成功'
                // })
                console.log(res3.data);
                if (res3.data.code == 1001) {
                    t.setData({
                        condeShow: !is,
                        fileLists_code: []
                    })
                    wx.showToast({
                        title: res3.data.msg,
                        icon: 'none',
                        duration: 3000
                    })
                } else {
                    wx.showToast({
                        title: res3.data.msg,
                        icon: 'none',
                        duration: 3000
                    })
                    t.setData({
                        fileLists_code: []
                    })
                }
            }
        })
    },

    goPageBtn(e) {
        if (!wx.getStorageSync('user_id3')) {
            this.goLoginBtn()
            return
        }

        const {
            url
        } = e.currentTarget.dataset

        wx.navigateTo({
            url
        })
    }
})